package cn.jdy.plugins.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.AjaxUtilCtrl;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.SMSUtil;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Mall;
import cn.jdy.plugins.entity.Productx;
import cn.jdy.plugins.service.MallService;
import cn.jdy.plugins.service.ProductxService;

/**
 * @title 商家管理web前台操作
 * @author jga
 * @since 3-12-2015
 */

@Controller
@RequestMapping("/mall")
public class MallCtrl extends BaseCtrl{
	@Autowired
	private MallService MallService;
	@Autowired
	private ConfService confService;

  @Autowired
  private ProductxService productxService;
	/**
	 *  商家列表
	 */
  @RequestMapping("")
	public ModelAndView list(Mall entity, String fromDate, String toDate) {
	  ModelAndView mv = new ModelAndView("/mall/mallList.jsp");
    try {
      //设置分页信息
      if(entity.getiDisplayLength() == 0) entity.setiDisplayLength(10);                //默认长度5
      if(entity.getPageNo()<=0) entity.setPageNo(1);                                  //默认页数1
      entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength());  //显示起始索引
   //  if(entity.getColumnId()==null){//9810
    //   entity.setColumnId(entity.getCv().getId());
     //   }
      if(entity.getBy1()!=null&&!",".equals(entity.getBy1())){//判断不为空和，
          if(entity.getBy1().split(",").length>1){
            entity.setColumnId(Long.valueOf(entity.getBy1().split(",")[1]));
            }else{  //
              entity.setColumnId(Long.valueOf(entity.getBy1().split(",")[0]));
            }
          mv.addObject("classlist", confService.findConfValueByPid(Long.valueOf(entity.getBy1().split(",")[0])));
          }
      entity.setStatus("1");
      mv.addObject("dataList", MallService.query(entity));
      mv.addObject("iTotalDisplayRecords", MallService.count(entity));
      mv.addObject("pageNo", entity.getPageNo());
      mv.addObject("size", entity.getiDisplayLength());
      mv.addObject("total", MallService.count(entity));
      mv.addObject("entity", entity);    
      mv.addObject("key", entity.getKeyword());    
  
    } catch(Exception e) {
      BaseLog.e(this.getClass(), "查询异常", e);
    }

		return mv;
	}
	
	/**
	 * 异步查询
	 * @param sp
	 * @param fromDate
	 * @param toDate
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Mall sp){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
	
			jsonMap.put("dataList", MallService.querypage(sp));
			jsonMap.put("iTotalDisplayRecords", MallService.count(sp));
			jsonMap.put("iTotalRecords", MallService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}
	
	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/show-{id}.html")
	public ModelAndView edit(@PathVariable Integer id) {
		ModelAndView mv = new ModelAndView("/mall/mallDetail.jsp");
		mv.addObject("data", id==null||id==0 ? id : this.MallService.find(id));
		 if(id!=null){
		   Productx px=new Productx();
		 //  Mall m=new Mall();
		//   m.setId(id);
		 //  px.setMall(m);
       DetachedCriteria dc = DetachedCriteria.forClass(px.getClass());
       dc.add(Restrictions.eq("mallId", id));
  //     dc.addOrder(Order.desc("createTime"));
		   List<Productx> list=   productxService.find(dc,0,4);
		   mv.addObject("plist",list);
		 }
		return mv;
	}
	
	 @RequestMapping("/showadd-{id}.html")
	  public ModelAndView queryadd(@PathVariable Integer id) {
	    ModelAndView mv = new ModelAndView("/mallAddress.jsp");
	    mv.addObject("dataadd", id==null||id==0 ? id : this.MallService.find(id));
	    return mv;
	  }
	
	 /**
	  * 查询子分类
	   * @param pid
	   * @return 
	   */
	  @RequestMapping("/queryConfTByPid")
	  @ResponseBody
	  public Map<String, Object> queryConfTByPid(Long pid) {
	    Map<String, Object> jsonMap = new HashMap<>();
	    try {
	      jsonMap.put("dataList", confService.findConfValueByPid(pid));
	      jsonMap.put("statusCode", 200);
	    } catch(Exception e) {
	      jsonMap.put("statusCode", 500);
	      BaseLog.e(this.getClass(), "查询配置异常", e);
	    }
	    return jsonMap;
	  }
	  /**
	   * @return 
	   * @title : 保存注册商家信息
	   * @description: 保存注册信息 跳转到首页或前一个页面
	   * @author: wuzhiliang
	   * @date: 2014-03-13 16:53
	   */
	  @RequestMapping("/forSaveMember")
	  public ModelAndView forSaveRegisterMember(Mall memberBo,String authcode) {
	    ModelAndView mv = new ModelAndView();
	 /*   if(null == request.getSession().getAttribute(GlobalConstant._PHONECODE)||!authcode.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))){
	      mv.setViewName("/registerMall.jsp");
	      mv.addObject("msg", "短信验证码无效！");
	      return mv;
	    }*/
	      
	    try {
	      memberBo.setStatus("0");
	      memberBo.setPassword(SafeUtil.md5(memberBo.getPassword()).substring(8, 16));
	      memberBo.setCreateTime(DateUtil.getCurrentTime());
	      MallService.save(memberBo);
	    //  session.setAttribute("user", memberBo);
	     // mv.addObject("msg", "提交成功，我们将在2-3个工作日联系你");
	      mv.setViewName("/");
	    } catch(BaseException e) {
	      mv.setViewName("/registerMall.jsp");
	      mv.addObject("msg", "注册失败！");
	      BaseLog.e(this.getClass(), "保存会员注册信息错误", e);
	    }
	    return mv;
	  }
	  
	  /**
	   * 注册 发送手机验证码
	   */
	  @RequestMapping("/registeredPhoneCode")
	  @ResponseBody
	  public Map<String, Object> registeredPhoneCode(String phonecode, String vcode) {
	    Map<String, Object> jsonMap = new HashMap<String, Object>();
	    try {
	      String code = (String) session.getAttribute("verifyCode");
	      if(null == phonecode || "".equals(phonecode) || null == vcode || "".equals(vcode) || code == null || "".equals(code) || !code.equals(vcode)){
	          jsonMap.put("success", "500");
	          jsonMap.put("reMsg", "验证码不对");
	      }else{
	        if(code.equals(vcode)){
	          if(memberService.findcheckUsermobile(phonecode) > 0) {
	            jsonMap.put("success", "500");
	            jsonMap.put("reMsg", "该手机号已被注册");
	          }else{
	          //  sendMsg(phonecode);
	            jsonMap.put("success", "0");
	          }
	        }
	      }
	    } catch(Exception e) {
	      jsonMap.put("success", "500");
	      BaseLog.e(AjaxUtilCtrl.class, "发送短信验证码异常", e);
	    }
	    
	    return jsonMap;
	  }
	   /**
     * 短信接口
     */
	  private void sendMsg(String phonecode) throws IOException{
	    if(phonecode.matches("^1\\d{10}$")){
	      // 生成6位随机数
	      String mobileCode = (Math.random() + "").substring(2, 8);// 生成验证码 6位数字验证码
	  
	      session.setAttribute(GlobalConstant._PHONECODE,mobileCode);
	      
	      try {
//	      String res = SMSUtil.sms10690071(phonecode, mobileCode);
	        String res = SMSUtil.yuntongxun(phonecode,mobileCode,"10");
	        BaseLog.d(AjaxUtilCtrl.class, res);
	      } catch (Exception e) {
	        BaseLog.e(AjaxUtilCtrl.class, "短信验证码发送异常", e);
	      }
	    }
	  }
}
